import os

import tornado.ioloop
import tornado.web
import tornado.websocket
# import tornado.httpserver


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('chat.html')


class ChatHandler(tornado.websocket.WebSocketHandler):
    users = set()  # 多client的写法

    def open(self):
        print('new connection')
        self.users.add(self)

        for u in self.users:
            u.write_message('new connection')

    def on_message(self, message):
        for u in self.users:
            u.write_message(f'{self.request.remote_ip}: {message}')
        # self.write_message(u"You said: " + message)

    def on_close(self):
        self.users.remove(self)
        print(f'{self.request.remote_ip} connection closed')

    def check_origin(self, origin: str) -> bool:
        # return super().check_origin(origin)
        return True

    # def on_error(self, error):
    #     print('connection error')

    # def on_ping(self, data):
    #     print('ping received')

    # def on_pong(self, data):
    #     print('pong received')


def make_app():
    return tornado.web.Application(
        [
            (r'/', IndexHandler),
            (r'/chat', ChatHandler),  # add websocket url
        ],
        debug=True,
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
    )


if __name__ == '__main__':
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
